﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GtsServer.Service.Model;
using GtsServer.DAL;
using GtsServer.Common;
using System.Data;
using System.Security.Cryptography;
using System.IO;

namespace GtsServer.Service.Controller
{
    public class ChargeController
    {
        public ChargeZfbResponse ChargeZfb(ChargeZfbRequest request)
        {
            ChargeZfbResponse response = new ChargeZfbResponse()
            {
                alipay = new ChargeZfbManage(),
                control = new ChargeControl()
            };

            string userAccount = BaseController.Account(request.info);

            if (string.IsNullOrEmpty(userAccount))
                return response;

            OrderDAL dal = new OrderDAL();
            DataSet ds = dal.AddOrder(userAccount, request.charge.type, request.charge.mode, request.charge.appid, request.charge.chargeid, request.charge.gametype, request.charge.matchid, Convert.ToDecimal(request.charge.money) / 100, request.info.phone.pid);
            string orderID = string.Empty;
            string prizeName = string.Empty;
            string prizeDesc = string.Empty;
            string timer = string.Empty;
            if (ds.Tables[0].Rows.Count > 0)
            {
                orderID = ds.Tables[0].Rows[0]["orderAccount"].ToString();
                prizeName = ds.Tables[0].Rows[0]["Name"].ToString();
                prizeDesc = ds.Tables[0].Rows[0]["Remark"].ToString();
                timer = ds.Tables[0].Rows[0]["timer"].ToString();
            }

            //合作商户ID  
            string partner = CommonConfig.partner;//"160629";
            //卖家帐号
            string seller = CommonConfig.apilyAccount;
            // 外部交易号 这里取当前时间，商户可根据自己的情况修改此参数，但保证唯一性
            string outTradeNo = orderID;
            //获取商品名称
            string subject = prizeName;
            //获取商品描述
            string body = prizeDesc;
            //获取商品金额
            string totalFee = (request.charge.money / 100.00).ToString();
            //notify_url通知地址
            string notify_url = CommonConfig.apilyCallBackUrl;
            //组装待签名数据
            string signData = "partner=\"" + partner + "\"";
            signData += "&";
            signData += "seller=\"" + seller + "\"";
            signData += "&";
            signData += "out_trade_no=\"" + outTradeNo + "\"";
            signData += "&";
            signData += "subject=\"" + subject + "\"";
            signData += "&";
            signData += "body=\"" + body + "\"";
            signData += "&";
            signData += "total_fee=\"" + totalFee + "\"";
            signData += "&";
            signData += "notify_url=\"" + notify_url + "\"";
            // modelist = "\"zfb_list\":{\"zfb\":{\"zfb_url\":\"" + signData + "\"}},";
            response.control = new ChargeControl()
            {
                timer = timer,
                sms = "0",
                charge_url = "",
                regular = request.charge.mode
            };
            response.alipay.url = signData;

            return response;
        }

        public ChargeSzfResponse ChargeSzf(ChargingSzfRequest request)
        {
            ChargeSzfResponse response = new ChargeSzfResponse()
            {
                szf = new ChargeSzfManage(),
                control = new ChargeControl()
            };

            string userAccount = BaseController.Account(request.info);

            if (string.IsNullOrEmpty(userAccount))
                return response;

            OrderDAL dal = new OrderDAL();

            string card = request.szf.card;//卡号（神州付）
            string pwd = request.szf.pwd; //密码
            decimal price = request.szf.price; //面值
            string plmn = request.info.sim.plmn;//sim卡的plmn号码
            int op = request.szf.op;//运营商

            DataSet ds = dal.AddOrderSzf(userAccount, request.charge.type, 2, request.charge.appid, request.charge.chargeid, request.charge.gametype, request.charge.matchid,
                Convert.ToDecimal(request.charge.money) / 100, request.info.phone.pid, card, pwd, price, op);
            string orderID = string.Empty;
            string prizeName = string.Empty;
            string prizeDesc = string.Empty;
            string timer = string.Empty;
            if (ds.Tables[0].Rows.Count > 0)
            {
                orderID = ds.Tables[0].Rows[0]["orderAccount"].ToString();
                prizeName = ds.Tables[0].Rows[0]["Name"].ToString();
                prizeDesc = ds.Tables[0].Rows[0]["Remark"].ToString();
                timer = ds.Tables[0].Rows[0]["timer"].ToString();
            }

            string cardInfo = UrlDecode.DesEncode(string.Format("{0}@{1}@{2}", price, card, pwd), CommonConfig.szfDesKey);

            //组织支付请求数据
            string privateKey = CommonConfig.szfprivateKey;
            string version = CommonConfig.szfVersion;//版本号 *
            string merId = CommonConfig.szfMerId;//商户ID *
            string payMoney = request.charge.money.ToString();//支付金额(单位：分) *
            string orderId = orderID;//订单号（格式：yyyyMMdd-merId-SN） * 
            string pageReturnUrl = "";//页面返回地址
            string serverReturnUrl = CommonConfig.szfCallbackUrl;//服务器返回地址
            string merUserName = CommonConfig.szfMerUserMail;//商户的用户姓名
            string merUserMail = CommonConfig.szfMerUserMail;//商户的用户Email
            string itemName = "";//产品名称
            string itemDesc = "";//产品描述
            string bankId = "";//平台银行ID
            string privateField = "";//商户私有数据
            string gatewayId = "";//支付方式id
            string cardTypeCombine = "0"; //移动充值卡（神州行卡）支付
            string verifyType = "1";//数据校验方式
            string returnType = "3";//返回结果方式
            string isDebug = "0";//是否调试

            string md5String = version + merId + payMoney + orderId + serverReturnUrl + cardInfo + privateField + verifyType + privateKey;
            //md5String = md5String.MD5CSP();
            md5String = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(md5String, "MD5").ToLower();

            //商户似有数据privateField为空  
            string url = string.Format("{0}?version={1}&merId={2}&payMoney={3}&orderId={4}&returnUrl={5}&cardInfo={6}&merUserName={7}&merUserMail={8}&privateField={9}&verifyType={10}&cardTypeCombine={11}&md5String={12}&signString=",
                        CommonConfig.szfUrl, version, merId, payMoney, orderID, serverReturnUrl, System.Web.HttpUtility.UrlEncode(cardInfo), CommonConfig.szfMerUserMail, CommonConfig.szfMerUserMail, "", 1, op, md5String);

            response.control = new ChargeControl()
            {
                timer = timer,
                sms = "0",
                charge_url = "",
                regular = request.charge.mode
            };
            response.szf.url = url;

            return response;
        }

        public void ChargeCommon(ChargeCommonRequest request)
        {
            LogHelper.WriteLog(JsonHelper.ToJson(request));
            OrderDAL dal = new OrderDAL();
            //计费方式：1：支付宝:；2：神州付； 3：短信； 4：银联
            if (request.Body.mode == 2)
            {
                DataSet ds = dal.AddCommonOrderSzf(request.Body.sys_account, 0, request.Body.mode, 1001, request.Body.chargeid, request.Body.gametype, request.Body.matchid,
                Convert.ToDecimal(request.Body.money) / 100, 0, request.Body.szf.card, request.Body.szf.pwd, request.Body.szf.price, request.Body.szf.op, request.OrderID);
            }
            else
            {
                DataSet ds = dal.AddCommonOrder(request.Body.sys_account, 0, request.Body.mode, 1001, request.Body.chargeid, request.Body.gametype, request.Body.matchid, Convert.ToDecimal(request.Body.money) / 100, 0,request.OrderID);
            }
        }
    }
}
